<script setup>
const props = defineProps({
  content: {
    type: String,
    default: '',
  },
  lineHeight: {
    type: Number,
    default: 42,
  },
  maxLine: {
    type: Number,
    default: 2,
  },
  itemIndex: {
    type: Number,
    default: 0,
  },
})

const showExpand = ref(false)

const isExpand = ref(true)

const toggleExpand = () => {
  isExpand.value = !isExpand.value
}

const computedStyle = computed(() => {
  return {
    'line-height': `${props.lineHeight}rpx`,
    height: isExpand.value ? 'auto' : `${props.lineHeight * props.maxLine}rpx`,
  }
})

const instance = getCurrentInstance()

// 检查内容是否超过指定行数
const checkContentLines = () => {
  // 确保DOM已经更新
  nextTick(() => {
    // 创建查询对象 - 兼容不同平台
    const query = uni.createSelectorQuery().in(instance.proxy)

    query
      .select(`#content_box`)
      .boundingClientRect((rect) => {
        console.log('checkContentLines rect', rect)
        if (rect) {
          // 计算实际行数
          const actualLines = Math.ceil(rect.height / props.lineHeight)
          if (actualLines > props.maxLine) {
            isExpand.value = false
            showExpand.value = true
          }
        }
      })
      .exec()
  })
}

watch(
  () => props.content,
  (newVal) => {
    console.log('watch content', newVal)
    if (newVal) {
      checkContentLines()
    }
  },
  {
    immediate: true,
  },
)

// onReady(() => {
//   nextTick(() => {
//     uni.createSelectorQuery().select(`.content-${props.itemIndex}`).boundingClientRect((rect) => {
//       console.log('rect', rect)
//       // if (rect.scrollHeight > props.lineHeight * props.maxLine) {
//       //   showExpand.value = true
//       //   isExpand.value = false
//       // }
//     }).exec()
//   })
// })
</script>

<template>
  <view class="collapse-box">
    <view
      id="content_box"
      class="content"
      :class="`content-${itemIndex}`"
      :style="computedStyle"
    >
      {{ content }}
    </view>
    <view
      v-if="showExpand"
      class="expand"
      @click.stop="toggleExpand"
    >
      <text>
        {{ isExpand ? '收起' : '展开' }}
      </text>
      <wd-icon
        v-if="isExpand"
        name="chevron-up"
        size="40rpx"
      ></wd-icon>
      <wd-icon
        v-else
        name="chevron-down"
        size="40rpx"
      ></wd-icon>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.content {
  font-size: 28rpx;
  color: $uni-text-color-grey;
  overflow: hidden;
}

.expand {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60rpx;
  color: $uni-color-primary;
  font-size: 24rpx;
}
</style>
